import React, { useState, useEffect } from 'react';
import styles from '../css/scenicdetails.module.css'; // 引入新的 CSS 文件
import left from '../assets/left.png';
import hourse3 from '../assets/hourse3.png';
import { useNavigate } from 'react-router-dom';
import ling from '../assets/ling.png';
import position from '../assets/position.png';
import maps from '../assets/maps.png';
import talk from '../assets/talk.png';
import right1 from '../assets/right1.png';
import right from '../assets/right.png';
import have from '../assets/vioce.png';
import write from '../assets/write.png';
import contact from '../assets/contact.png';
import clock from '../assets/clock.png';
import unload from '../assets/download.png';
import star from '../assets/redstar.png';
import good from '../assets/good.png';
import three from '../assets/three.png';
import avatar from '../assets/avatar.jpg';
import defaultImg from '../assets/pandaback.png'; // 新增导入 defaultImg
import { Switch, Toast } from 'antd-mobile'; // 在这里添加Toast导入
import { BaseUrl } from '../config';//前缀
import {
  getCommentData,
} from '../api/scenicdetails';
import {
  getScenicTickets
} from '../api/scenicData';
// 须知弹窗组件
const Alert = ({ isOpen, onClose }) => {
  if (!isOpen) return null;
  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      backgroundColor: 'rgba(0, 0, 0, 0.5)', // 半透明黑色背景
      zIndex: 999
    }}>
      <div style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        width: '100%',
        backgroundColor: '#fff',
        padding: '20px',
        boxShadow: '0 -2px 10px rgba(0, 0, 0, 0.1)',
        zIndex: 1000
      }}>
        <div className={styles.alertone}>
          <p>购买须知</p>
          <div className={styles.buy}>
            <b>购买须知</b>
            <div className={styles.buyFont}>
              <p>可订明日</p>
              <span>可订明日，需出行当天的07:29前购买</span>
            </div>
            <div className={styles.buyFont}>
              <p>出票速度</p>
              <span>平均34秒出票</span>
            </div>
            <div className={styles.buyFont}>
              <p>无需换票</p>
              <span>无需换票，【凭身份证】直接入园</span>
            </div>
            <div className={styles.buyFonts}>
              <p>随时退</p>
              <span>使用日期后1天经核实未使用系统将<br />自动发起退款请求。<br />下单后不支持改期</span>
            </div>
          </div>
          <div className={styles.buyOne}>
            <b>使用说明</b>
            <div className={styles.use}>
              <p>可订明日</p>
              <span>指定出行日期起7天内，可任意选择一<br />天入园</span>
            </div>
            <div className={styles.uses}>
              <p>可订明日</p>
              <span>08:30-17:00</span>
            </div>
            <div className={styles.uses}>
              <p>可订明日</p>
              <span>景区名称&nbsp;检票口</span>
            </div>
          </div>
          <div className={styles.close} onClick={onClose}>关闭</div>
        </div>
      </div>
    </div>
  );
};

// 顶部导航栏组件
const TopNavigation = ({ onLeftClick, onFirstClick }) => {
  const navigate = useNavigate();

  const handleHomeClick = () => {
    navigate('/home'); // Navigate to home route
  };

  return (
    <div className={styles.top}>
      <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', width: '45%', justifyContent: 'space-between' }}>
        <div className={styles.left}>
          <img src={left} alt="" onClick={() => navigate(-1)} />
          <div className={styles.line}></div>
          <img id="hourse" src={hourse3} alt="" onClick={handleHomeClick} />
        </div>
      </div>
      <p>景区详情</p>
    </div>
  );
};

// 图片和视频展示组件
const ImageAndVideo = ({ onVideoBtnClick, onImgBtnClick, onPhotoAlbumClick, onMusicClick, videoMusic, videoSrc, imgSrc, jingdatas }) => {
  const navigate = useNavigate();

  const handleMusic = () => {
    const videoElement = document.getElementById('videos'); // 获取视频元素
    if (videoElement) {
      videoElement.muted = !videoElement.muted; // 切换静音状态
    }
  };

  return (
    <div className={styles.big} style={{ marginTop: 40 }}>
      <div className={styles.image}>
        <div className={styles.images}>
          {videoMusic ? (
            <video id="videos" src={videoSrc} controls autoPlay loop x5-video-player-type='h5-page' webkit-playsinline="true" x5-video-player-fullscreen="true"></video>
          ) : (
            <img src={imgSrc} alt="" />
          )}
        </div>
        <div className={styles.bottoms}>
          <div className={styles.bottom}>
            <div className={styles.vAndi}>
              <Switch
                checked={videoMusic}
                onChange={(checked) => {
                  checked ? onVideoBtnClick() : onImgBtnClick();
                }}
                checkedText="视频"
                uncheckedText="图片"
                activeColor="#FFFFFF"
                inactiveColor="#5F5B50"
              />
            </div>
            <div className={styles.photo} onClick={onPhotoAlbumClick}>
              <span>相册</span>
              <img src={right} alt="" />
            </div>
            <div className={styles.music} onClick={handleMusic}>
              <img id="musics" src={have} alt="" />
            </div>
          </div>
        </div>
      </div>
      <div className={styles.before}>
        <div><img src={ling} alt="" />
          <p>票务提前预定通知</p>
        </div>
      </div>
      <div className={styles.title}>
        <div className={styles.fif}>
          <b>{jingdatas ? jingdatas.name : "五龙山野生动物王国"}</b>
          <p> # 秋日游园</p>
        </div>
        <div className={styles.four}>
          <div className={styles.max} style={{ width: '70px', height: '50px', marginRight: '15px' }}>
            <div style={{ width: '100%', height: '50%', backgroundColor: '#ffeb3b', borderRadius: '6px 6px 0px 0px' }}>
              <b style={{ fontSize: '18px', marginLeft: '0' }} id="score">{jingdatas ? jingdatas.score : "8.0"}</b>
            </div>
            <div style={{ width: '100%', height: '50%', backgroundColor: '#ded8a3', borderRadius: '0 0 8px 8px' }}>
              <span style={{ fontSize: '14px', color: '#585858' }}><span id="cont">{jingdatas ? jingdatas.number : "8"}</span>评价</span>
            </div>
          </div>
        </div>
      </div>
      <div className={styles.twoBlock}>
        <p className={styles.play}>游玩榜</p>
        <p className={styles.new}><span id="adresing">{jingdatas ? jingdatas.address.split(' ')[0] : "新乡"}</span>&nbsp;景区榜第1名</p>
      </div>
      <div className={styles.green}>
        <b>今日开放</b>
        <br />
        <span id="star_time">{jingdatas ? jingdatas.start_time : "09-23-18:00,16:00停止入场"}</span>
      </div>
      <div className={styles.Three}>
        <div>门票价格实拍图</div>
        <div>公益景区</div>
        <div>有停车场</div>
      </div>
      <div className={styles.imageBack}>
        <div style={{ width: '70%' }}>
          <b id="address">{jingdatas ? jingdatas.address : "辉县市响水河有了西边"}</b>
          <div className={styles.postion}>
            <img src={position} alt="" />
            <span>距离您有 <span id="zero">0</span> 公里</span>
          </div>
        </div>
        <div className={styles.postionImg}>
          <div onClick={() => navigate('/maps')}>
            <img src={maps} alt="" />
            <span>地图</span>
          </div>
          <a href={`tel:${jingdatas ? jingdatas.tel : ""}`}>
            <div>
              <img src={talk} alt="" />
              <span>客服</span>
            </div>
          </a>
        </div>
      </div>
      <div className={styles.look}>
        <b>游玩指南</b>
        <div style={{ display: 'flex', alignItems: 'center' }} onClick={onPhotoAlbumClick}>
          <span>查看全部</span>
          <img src={right1} alt="" />
        </div>
      </div>
      <div className={styles.imgBlock}>
        {/* 这里可以根据数据动态生成图片块 */}
      </div>
    </div>
  );
};

// 门票信息组件
// 门票信息组件
// 门票信息组件
const TicketInfo = ({ ticketData, onGobuyClick, onReserveClick }) => {
  const flattenedTickets = ticketData.reduce((acc, item) => {
    if (item.children && item.children.length > 0) {
      return acc.concat(item.children);
    }
    return acc;
  }, []);

  return (
    <div className={styles.ticketTwo}>
      <b>门票</b>
      <div className={styles.twoBlocks}>
        {flattenedTickets.map((childItem, index) => (
          <React.Fragment key={index}>
            <div style={{ marginTop: 5 }}>
              <div className={styles.adult}>
                <div><b>{childItem.name}</b><del>￥{childItem.original_price}</del></div>
              </div>
              <div className={styles.day}>
                <div><span style={{ marginLeft: 10, color: '#0aa1f9' }}>可订明日</span>
                  <p style={{ fontSize: 13, color: 'red' }}>￥<span style={{ fontSize: 16 }}>{childItem.current_price}</span><span style={{ fontSize: 15, color: '#585453' }}>起</span></p>
                </div>
              </div>
              <div className={styles.retreat}>
                <div><span style={{ marginLeft: 10, color: '#0aa1f9' }}>随时退，无需退票</span>
                  <p>优惠￥10</p>
                </div>
              </div>
              <div className={styles.reserve}>
                <div><span style={{ marginLeft: 10, color: '#0aa1f9', color: '#535453' }} onClick={() => onGobuyClick(index)}>购买须知<img src={right1} alt="" /></span>
                  <p onClick={() => onReserveClick(index)}>预定</p>
                </div>
              </div>
            </div>
            {index < flattenedTickets.length - 1 && (
              <div style={{ borderBottom: '1px solid #e0e0e0', margin: '10px 0' }}></div>
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
};

// 评论列表组件
const CommentList = ({ comments }) => {
  const handleImageError = (e) => {
    e.target.src = defaultImg; // 使用事件目标的src属性设置默认图片
  };
  return (
    <div className={styles.bigComment} style={{ paddingBottom: '55px' }}>
      {/* 新增的评论标题和查看全部 */}
      <div className={styles.look}>
        <b>评论</b>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span>查看全部</span>
          <img src={right1} alt="" />
        </div>
      </div>

      {comments.length === 0 ? (
        <p id="none">暂无评论...</p>
      ) : (
        comments.map((comment, index) => (
          <div key={index} className={styles.commentItem}>
            <div className={styles.coment}>
              <img src={comment.avatar} alt="" onError={handleImageError} />
              <div style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                  <span>{comment.name}</span>
                  <span style={{ marginRight: 20 }}>{comment.create_time}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', marginTop: 10 }}>
                  <p>评分</p>
                  <img style={{ width: '20px', height: '20px' }} src={star} alt="" />
                  <img style={{ width: '20px', height: '20px' }} src={star} alt="" />
                  <img style={{ width: '20px', height: '20px' }} src={star} alt="" />
                  <img style={{ width: '20px', height: '20px' }} src={star} alt="" />
                </div>
              </div>
            </div>
            <div className={styles.contentFont}>
              <span style={{ marginLeft: '15px' }}>{comment.content}</span>
            </div>
            <div className={styles.commentImg}>
              {Array.isArray(comment.img) && comment.img.length > 0 && comment.img.map((imgSrc, imgIndex) => (
                <img key={imgIndex} src={imgSrc} alt="" />
              ))}
            </div>
            <div className={styles.browse}>
              <span>浏览{comment.number}</span>
              <div>
                <img src={good} alt="" />
                <img src={three} alt="" />
              </div>
            </div>
            {comment.children && comment.children.length > 0 && (
              <div className={styles.returns}>
                {comment.children.map((child, childIndex) => (
                  <div key={childIndex}>
                    <span>{child.name}：</span>
                    <p>{child.content}</p>
                  </div>
                ))}
              </div>
            )}
          </div>
        ))
      )}
    </div>
  );
};

// 底部操作栏组件
const BottomActions = ({ onWriteComClick, onLookDoorClick, onTicketClick }) => {
  return (
    <div className={styles.bottomer}>
      <div className={styles.bottomOne}>
        <div className={styles.write} onClick={onWriteComClick}>
          <img src={write} alt="" />
          <span>写评论</span>
        </div>
        <div className={styles.write}>
          <img src={contact} alt="" />
          <span>景点讲解</span>
        </div>
        <div className={styles.write} onClick={onLookDoorClick}>
          <img src={clock} alt="" />
          <span>演出预告</span>
        </div>
      </div>
      <div className={styles.bottomTwo}>
        <div className={styles.lookDoor} onClick={onTicketClick}>
          <img src={unload} alt="" />
          <b>查看门票</b>
        </div>
      </div>
    </div>
  );
};

// 主景区详情页面组件
const ScenicDetails = () => {
  const navigate = useNavigate(); // 获取 navigate 函数

  const [isAlertOpen, setIsAlertOpen] = useState(false);
  const [videoMusic, setVideoMusic] = useState(false);
  const [ticketData, setTicketData] = useState([
    {
      name: '成人票',
      original_price: 90,
      current_price: 90
    }
  ]);
  const [comments, setComments] = useState([]);
  const [videoSrc, setVideoSrc] = useState('');
  const [imgSrc, setImgSrc] = useState(''); // 新增状态用于存储图片路径
  const scenicId = sessionStorage.getItem('jingid');
  const [jingdatas, setJingdatas] = useState('');
  const [reservedTickets, setReservedTickets] = useState([]); // 新增状态用于存储预定数据
  const [showBottomActions, setShowBottomActions] = useState(true); // 新增状态控制底部栏显示
  useEffect(() => {
    console.log(111111113456781, JSON.parse(sessionStorage.getItem("jingdata")));
    // 页面加载时刷新页面
    setJingdatas(JSON.parse(sessionStorage.getItem("jingdata")));
  }, []);

  // 在ScenicDetails组件中修改数据获取部分
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 从sessionStorage获取景区数据
        const jingdata = JSON.parse(sessionStorage.getItem("jingdata"));
        setJingdatas(jingdata);

        // 并行获取所有数据
        const [ticketResult, commentResult] = await Promise.all([
          getScenicTickets(scenicId),
          getCommentData(scenicId)
        ]);

        console.log('Ticketing index response:', ticketResult);
        console.log('Scenicom index response:', commentResult);

        setTicketData(ticketResult.data);
        setComments(commentResult.data);

        // 存储数据到sessionStorage
        sessionStorage.setItem('ticketData', JSON.stringify(ticketResult.data));

        if (jingdata) {
          const video = `${BaseUrl}${jingdata.video}`;
          const img = `${BaseUrl}${jingdata.img}`;
          setVideoSrc(video);
          setImgSrc(img);
          sessionStorage.setItem('video', video);
          sessionStorage.setItem('img', img);
          sessionStorage.setItem('scenicName', jingdata.name);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        Toast.show({
          content: '数据加载失败',
          position: 'top',
        });
      }
    };

    fetchData();
  }, [scenicId]);

  const onLeftClick = () => {
    // 处理返回操作
  };

  const onFirstClick = () => {
    // 处理跳转首页操作
  };

  const onVideoBtnClick = () => {
    setVideoMusic(true);
  };

  const onImgBtnClick = () => {
    setVideoMusic(false);
  };
  const handleMusic = () => {
    const videoElement = document.getElementById('videos'); // 获取视频元素
    if (videoElement) {
      videoElement.muted = !videoElement.muted; // 切换静音状态
    }
  };
  const onPhotoAlbumClick = () => {
    // 存储景区名称
    const scenicName = jingdatas ? jingdatas.name : "五龙山野生动物王国";
    sessionStorage.setItem('scenicName', scenicName);
    // 打印临时存储的景区名称和门票列表
    const storedScenicName = sessionStorage.getItem('scenicName');
    const ticketData = JSON.parse(sessionStorage.getItem('ticketData'));
    console.log('景区名称:', storedScenicName);
    console.log('门票列表:', ticketData);
    navigate("/photoAlbum");
    console.log("跳转相册");
  };

  const onMusicClick = () => {
    setVideoMusic(!videoMusic);
  };

  const onGobuyClick = (index) => {
    setIsAlertOpen(true);
    const ticketsToBuy = ticketData.reduce((acc, item) => {
      if (item.children && item.children.length > 0) {
        return acc.concat(item.children);
      }
      return acc;
    }, []);
    const ticket = ticketsToBuy[index];
    if (!ticket) {
      console.error('Invalid ticket data at index:', index);
      return;
    }
    console.log('Ticket details:', ticket.deatils);
  };

  const onReserveClick = (index) => {
    const reservedTicket = ticketData.reduce((acc, item) => {
      if (item.children && item.children.length > 0) {
        return acc.concat(item.children);
      }
      return acc;
    }, [])[index];
    sessionStorage.setItem('reservedTicket', JSON.stringify(reservedTicket));
    setReservedTickets([...reservedTickets, reservedTicket]); // 存储预定数据
    console.log('Reserved Ticket:', reservedTicket); // 打印预定数据
    // 跳转到subOrder页面
    navigate('/suborder');
  };

  const onWriteComClick = () => {
    // 处理写评论操作
    navigate('/scenicname');
  };

  const onLookDoorClick = () => {
    // 处理演出预告操作
    navigate('/perform');
  };

  const onTicketClick = () => {
    navigate('/tickets'); // 跳转到门票页面
    setShowBottomActions(false); // 隐藏底部栏
  };

  const onCloseAlert = () => {
    setIsAlertOpen(false);
    setShowBottomActions(true); // 显示底部栏
  };

  return (
    <div style={{ backgroundColor: '#f4f4f4' }}>
      <Alert isOpen={isAlertOpen} onClose={onCloseAlert} />
      <TopNavigation onLeftClick={onLeftClick} onFirstClick={onFirstClick} />
      <ImageAndVideo
        onVideoBtnClick={onVideoBtnClick}
        onImgBtnClick={onImgBtnClick}
        onPhotoAlbumClick={onPhotoAlbumClick}
        onMusicClick={onMusicClick}
        videoMusic={videoMusic}
        videoSrc={videoSrc}
        imgSrc={imgSrc || "./img/10006.webp"} // 使用 imgSrc 状态
        jingdatas={jingdatas}
      />
      <TicketInfo ticketData={ticketData} onGobuyClick={onGobuyClick} onReserveClick={onReserveClick} />
      <CommentList comments={comments} />
      {showBottomActions && <BottomActions onWriteComClick={onWriteComClick} onLookDoorClick={onLookDoorClick} onTicketClick={onTicketClick} />}
      <div id="container"></div>
    </div>
  );
};

export default ScenicDetails;
